<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="filterState.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in list" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="filterState.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="filterHandler" type="primary" size="small">筛选</el-button>
            <el-button @click="resetFilterHandler" type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button @click="pubDialogVisible = true" type="primary" size="small" class="btn-pub">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table border stripe
        :data="artList"
        style="width: 100%">
        <el-table-column
          label="文章标题">
          <template v-slot="{row}">
            <el-link @click="showDetailHandler(row.id)" type="success">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column
            prop="cate_name"
            label="分类">
          </el-table-column>
          <el-table-column
            label="发表时间">
            <template v-slot="{row}">
              {{formatDate(row.pub_date)}}
            </template>
          </el-table-column>
          <el-table-column
            prop="state"
            label="状态">
          </el-table-column>
          <el-table-column
            label="操作">
            <template v-slot="{row}">
            <el-button @click="delHandler(row.id)" type="danger" size="mini">删除</el-button>
            </template>
          </el-table-column>
    </el-table>

      <el-pagination
        @size-change="sizeChangeHandler"
        @current-change="currentChangeHandler"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 分页区域 -->
        <el-dialog
        fullscreen
        title="发表文章"
        :visible.sync="pubDialogVisible"
        width="30%"
        :before-close="handleClose"
         @closed="pubClosedHandler">

         <el-form :model="pubForm" :rules="pubRules" ref="pubForm" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%">
            <!-- 循环创建 el-option, 下拉菜单项 -->
            <el-option
              v-for="item in list"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content">
          </quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img :src="previewImg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input @change="fileChangeHandler" type="file" style="display: none;" accept="image/*" ref="iptFileRef" />
          <!-- 选择封面的按钮 -->
          <el-button @click="$refs.iptFileRef.click()" type="text">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item prop="state">
          <el-button @click="pubArticleHandler('已发布')" type="primary">发布</el-button>
          <el-button @click="pubArticleHandler('草稿')" type="info">存为草稿</el-button>
        </el-form-item>
      </el-form>
        </el-dialog>

        <!-- 文章预览 -->
        <el-dialog
          title="文章预览"
          :visible.sync="previewVisible"
          width="70%">
          <h1 class="title">{{ artDetail.title }}</h1>

          <div class="info">
            <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
            <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
            <span>所属分类：{{ artDetail.cate_name }}</span>
            <span>状态：{{ artDetail.state }}</span>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <!-- 文章的封面 -->
          <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

          <!-- 文章的详情 -->
          <div v-html="artDetail.content" class="detail-box"></div>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
import coverImg from '../../../assets/images/cover.jpg'
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      filterState: {
        cate_id: '',
        state: ''
      },
      pubDialogVisible: false,
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择封面图片', trigger: 'blur' }]
      },
      list: [],
      previewImg: coverImg,
      artList: [],
      total: 0,
      previewVisible: false,
      artDetail: {}
    }
  },
  methods: {
    async handleClose (done) {
    //   this.$confirm('确认关闭？')
    //     .then(_ => {
    //       done()
    //     })
    //     .catch(_ => {})

      // 优化
      // 点击取消，则返回 cancel
      // 点击确认，则返回 confirm
      const result = await this.$confirm('确认关闭？').catch(e => e)
      if (result === 'confirm') done()
    },
    // 获取数据渲染
    async getCateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      //   console.log(res)
      // 提示获取失败
      if (res.code !== 0) return this.$message.error(res.message)

      // 数据赋值给 cateList
      this.list = res.data
    },
    // 文章封面处理
    fileChangeHandler (e) {
      // console.log(e)
      const files = e.target.files
      if (files.length === 0) {
        // this.pubForm.cover_img = null
        this.pubForm.cover_img = coverImg
      } else {
        this.pubForm.cover_img = files[0]

        // this.$refs.imgRef.src = URL.createObjectURL(files[0])
        this.previewImg = URL.createObjectURL(files[0])
      }
    },
    // 发布文章
    pubArticleHandler (state) {
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        this.pubForm.state = state

        const fd = new FormData()

        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // console.log(fd)
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // console.log(res)

        // 提示
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 重新渲染表格
        this.getArtList()

        // 关闭对话框
        this.pubDialogVisible = false
      })
    },
    // 清空表单
    pubClosedHandler () {
      // 清空表单
      // resetFields 的原理是根据 prop 指定的值来重置的, 非常好用!!!
      this.$refs.pubForm.resetFields()
      // 手动还原默认的图片
      this.previewImg = coverImg
    },
    // 获取表格数据
    async getArtList () {
      const { data: res } = await this.$http.get('/my/article/list', { params: { ...this.q } })
      // console.log(res)
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      }
    },
    // 时间函数
    formatDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    sizeChangeHandler (val) {
      // console.log(val)
      this.q.pagesize = val
      this.getArtList()
    },
    currentChangeHandler (val) {
      // console.log(val)
      this.q.pagenum = val
      this.getArtList()
    },
    // 筛选
    filterHandler () {
      this.q.cate_id = this.filterState.cate_id
      this.q.state = this.filterState.state
      this.q.pagenum = 1
      this.getArtList()
    },
    // 重置
    resetFilterHandler () {
      this.filterState.cate_id = ''
      this.filterState.state = ''
      // 清除所有状态, 重新发起请求
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArtList()
    },
    // 预览文章
    async showDetailHandler (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)

      this.artDetail = res.data
      this.previewVisible = true
    },
    // 删除功能
    delHandler (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        if (this.total % this.q.pagesize !== 0 && this.q.pagenum > 1) {
          this.q.pagenum--
        }

        this.getArtList()
      }).catch(e => e)
    }
  },
  created () {
    this.getCateList()
    this.getArtList()
  }

}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor{
    min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
